using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using UniversalAdmin.Application.Dtos;
using UniversalAdmin.Application.Services;
using UniversalAdmin.Application.Dtos.Log;
using UniversalAdmin.Application.Services.Interfaces;

namespace UniversalAdmin.Api.Controllers;

[ApiController]
[Route("api/[controller]")]
public class UserController : ControllerBase
{
    private readonly IUserService _userService;
    private readonly ILogService _logService;
    private readonly IUserContextService _userContextService;

    public UserController(IUserService userService, ILogService logService, IUserContextService userContextService)
    {
        _userService = userService;
        _logService = logService;
        _userContextService = userContextService;
    }

    /// <summary>
    /// 从JWT Token中获取当前用户ID
    /// </summary>
    /// <returns>当前用户ID，如果获取失败返回null</returns>
    private Guid? GetCurrentUserId()
    {
        var userIdClaim = User.FindFirst("userId");
        if (userIdClaim == null || !Guid.TryParse(userIdClaim.Value, out var userId))
        {
            return null;
        }
        return userId;
    }

    /// <summary>
    /// 记录操作日志
    /// </summary>
    /// <param name="action">操作类型</param>
    /// <param name="resource">资源类型</param>
    /// <param name="resourceId">资源ID</param>
    /// <param name="currentUserId">当前操作用户ID</param>
    private async Task LogOperation(string action, string resource, Guid? resourceId = null, Guid? currentUserId = null)
    {
        try
        {
            var logDto = new CreateLogDto
            {
                UserId = currentUserId ?? GetCurrentUserId(),
                Action = action,
                Resource = resource,
                ResourceId = resourceId,
                IpAddress = HttpContext.Connection.RemoteIpAddress?.ToString(),
                UserAgent = HttpContext.Request.Headers["User-Agent"].ToString()
            };
            await _logService.AddAsync(logDto);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"记录操作日志失败: {ex.Message}");
        }
    }

    [HttpGet]
    [Authorize]
    public async Task<IActionResult> GetAllUsers([FromQuery] PageRequestDto dto)
    {
        var list = await _userService.GetAllAsync(dto);
        
        // 移除重复的日志记录，由领域事件处理
        // await LogOperation("QueryList", "User");
        
        return Ok(new
        {
            code = 200,
            msg = "获取用户列表成功",
            data = list
        });
    }

    /// <summary>
    /// 获取当前登录用户信息（需要JWT认证）
    /// </summary>
    /// <returns>当前用户信息</returns>
    [HttpGet("current")]
    [Authorize] // 需要JWT认证
    public async Task<IActionResult> GetCurrentUser()
    {
        try
        {
            // 从JWT Token中获取用户ID
            var userIdClaim = User.FindFirst("userId");
            if (userIdClaim == null || !Guid.TryParse(userIdClaim.Value, out var userId))
            {
                return Unauthorized(new { code = 401, msg = "无效的用户信息" });
            }

            // 从数据库获取完整的用户信息
            var user = await _userService.GetByIdAsync(userId);
            if (user == null)
            {
                return NotFound(new { code = 404, msg = "用户不存在" });
            }

            return Ok(new
            {
                code = 200,
                msg = "获取当前用户信息成功",
                data = user
            });
        }
        catch (Exception ex)
        {
            return BadRequest(new { code = 400, msg = ex.Message });
        }
    }

    /// <summary>
    /// 获取当前用户信息（需要JWT认证）
    /// </summary>
    /// <returns>当前用户信息</returns>
    [HttpGet("profile")]
    [Authorize] // 需要JWT认证
    public async Task<IActionResult> GetCurrentUserProfile()
    {
        try
        {
            // 从JWT Token中获取用户ID
            var userIdClaim = User.FindFirst("userId");
            if (userIdClaim == null || !Guid.TryParse(userIdClaim.Value, out var userId))
            {
                return Unauthorized(new { code = 401, msg = "无效的用户信息" });
            }

            var user = await _userService.GetByIdAsync(userId);
            if (user == null)
            {
                return NotFound(new { code = 404, msg = "用户不存在" });
            }

            return Ok(new
            {
                code = 200,
                msg = "获取成功",
                data = user
            });
        }
        catch (Exception ex)
        {
            return BadRequest(new { code = 400, msg = ex.Message });
        }
    }

    [HttpPost("createrole/{userId}")]
    [Authorize]
    public async Task<IActionResult> CreateUserRole(Guid userId, [FromBody] AssignRole dto)
    {
        try
        {
            if (dto == null)
            {
                return BadRequest(new
                {
                    code = 400,
                    msg = "请求数据无效"
                });
            }

            if (dto.roleId == Guid.Empty)
            {
                return BadRequest(new
                {
                    code = 400,
                    msg = "角色ID无效"
                });
            }

            var result = await _userService.AssignRoleAsync(userId, dto.roleId);
            
            // 移除重复的日志记录，由领域事件处理
            // await LogOperation("AssignRole", "User", userId);
            
            return Ok(new
            {
                code = 200,
                msg = "角色分配成功",
                data = result
            });
        }
        catch (Exception ex)
        {
            return BadRequest(new
            {
                code = 400,
                msg = ex.Message
            });
        }
    }

    [HttpGet("{id}")]
    [Authorize]
    public async Task<IActionResult> GetById(Guid id)
    {
        var obj = await _userService.GetByIdAsync(id);
        
        // 移除重复的日志记录，由领域事件处理
        // await LogOperation("Query", "User", id);
        
        return Ok(new
        {
            code = 200,
            msg = "成功",
            data = obj
        });
    }

    [HttpGet("username/{username}")]
    [Authorize]
    public async Task<IActionResult> GetByUsername(string username)
    {
        var obj = await _userService.GetByUsernameAsync(username);
        if (obj == null)
        {
            return NotFound(new
            {
                code = 404,
                msg = "用户不存在",
                data = (object?)null
            });
        }
        
        // 移除重复的日志记录，由领域事件处理
        // await LogOperation("QueryByUsername", "User");
        
        return Ok(new
        {
            code = 200,
            msg = "获取用户信息成功",
            data = obj
        });
    }

    /// <summary>
    /// 根据用户名模糊查询用户
    /// </summary>
    /// <param name="username">用户名关键字</param>
    /// <returns>匹配的用户列表</returns>
    [HttpGet("search/username/{username}")]
    [Authorize]
    public async Task<IActionResult> GetByUsernameFuzzy(string username)
    {
        try
        {
            var users = await _userService.GetByUsernameFuzzyAsync(username);
            
            // 移除重复的日志记录，由领域事件处理
            // await LogOperation("QueryByUsernameFuzzy", "User");
            
            return Ok(new
            {
                code = 200,
                msg = "模糊查询用户成功",
                data = users
            });
        }
        catch (Exception ex)
        {
            return BadRequest(new
            {
                code = 400,
                msg = ex.Message
            });
        }
    }

    [HttpPost("create")]
    [Authorize]
    public async Task<IActionResult> CreateUser([FromBody] UsersDto dto)
    {
        var obj = await _userService.CreateAsync(dto);
        
        // 移除重复的日志记录，由领域事件处理
        // await LogOperation("Create", "User");
        
        return Ok(new
        {
            code = 200,
            data = obj
        });
    }

    [HttpDelete("delete/{id}")]
    [Authorize]
    public async Task<IActionResult> DeleteUser(Guid id)
    {
        var obj = await _userService.DeleteAsync(id);
        
        // 移除重复的日志记录，由领域事件处理
        // await LogOperation("Delete", "User", id);
        
        return Ok(new
        {
            code = 200,
            data = obj
        });
    }


    [HttpPut("update/{id}")]
    [Authorize]
    public async Task<IActionResult> UpdateUser(Guid id, [FromBody] UsersDto dto)
    {
        Console.WriteLine($"username  = {dto}");

        var obj = await _userService.UpdateAsync(id, dto);
        
        // 移除重复的日志记录，由领域事件处理
        // await LogOperation("Update", "User", id);
        
        return Ok(new
        {
            code = 200,
            data = obj
        });
    }

    [HttpPost("enable/{id}")]
    [Authorize]
    public async Task<IActionResult> EnableUser(Guid id)
    {
        await _userService.EnableAsync(id);
        
        // 移除重复的日志记录，由领域事件处理
        // await LogOperation("Enable", "User", id);
        
        return Ok(new
        {
            code = 200,
            msg = "用户已启用"
        });
    }

    [HttpPost("disable/{id}")]
    [Authorize]
    public async Task<IActionResult> DisableUser(Guid id)
    {
        var obj = await _userService.DisableAsync(id);
        
        // 移除重复的日志记录，由领域事件处理
        // await LogOperation("Disable", "User", id);
        
        return Ok(new
        {
            code = 200,
            data = obj
        });
    }

    [HttpPost("deleterole/{userId}")]
    [Authorize]
    public async Task<IActionResult> Removerole(Guid userId, [FromBody] AssignRole dto)
    {
        try
        {
            await _userService.RemoveRoleAsync(userId, dto.roleId);
            
            // 移除重复的日志记录，由领域事件处理
            // await LogOperation("RemoveRole", "User", userId);
            
            return Ok(new
            {
                code = 200,
                msg = "角色移除成功"
            });
        }
        catch (Exception ex)
        {
            return BadRequest(new
            {
                code = 400,
                msg = ex.Message
            });
        }
    }

    /// <summary>
    /// 根据用户ID查找角色
    /// </summary>
    /// <param name="userId">用户ID</param>
    /// <returns>用户及其角色信息</returns>
    [HttpGet("debug/{userId}/roles")]
    [Authorize]
    public async Task<IActionResult> GetUserRoles(Guid userId)
    {
        try
        {
            var result = await _userService.GetUserWithRolesAsync(userId);

            // 检查是否有错误
            var resultObj = result as object;
            if (resultObj != null)
            {
                var properties = resultObj.GetType().GetProperties();
                var errorProperty = properties.FirstOrDefault(p => p.Name == "error");
                if (errorProperty != null)
                {
                    var errorValue = errorProperty.GetValue(resultObj);
                    if (errorValue != null)
                    {
                        return NotFound(new
                        {
                            code = 404,
                            msg = errorValue.ToString(),
                            data = (object?)null
                        });
                    }
                }
            }

            // 记录查询操作日志
            // await LogOperation("QueryUserRoles", "User", userId);

            return Ok(new
            {
                code = 200,
                msg = "获取用户角色信息成功",
                data = result
            });
        }
        catch (Exception ex)
        {
            return BadRequest(new
            {
                code = 400,
                msg = ex.Message
            });
        }
    }

}
